package cn.com.connected.base.exception;


import cn.com.connected.base.utils.StringTools;
import lombok.extern.log4j.Log4j2;

import java.text.MessageFormat;

/**
 * 业务级别异常定义。
 *
 * @author
 */
@Log4j2
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = -418389432305176131L;
    //用作返回给前端标志
    private String retCode;
    //用作返回给前端备注
    private String retMsg;
    //用作系统日志
    private String otherMsg;

    private final static String basePackage = "connected";



    public BusinessException(ErrorCode errorCode, String retMsg) {
        log.error(getExceptionInfoTrace(retMsg));
        this.retMsg = retMsg;
        this.retCode=errorCode.getCode();
    }

    public BusinessException(ErrorCode errorCode) {
        log.error(getExceptionInfoTrace(errorCode.getMsg()));
        this.retMsg = errorCode.getMsg();
        this.retCode=errorCode.getCode();
    }


//    public BusinessException(ErrorCode errorCode,String formatInput,String... formatContent) {
//        log.error(getExceptionInfoTrace(errorCode.getMsg()));
//        this.retCode=errorCode.getCode();
//        this.retMsg = StringTools.format(formatInput,formatContent);
//    }

    public BusinessException(Throwable e,ErrorCode errorCode,String formatInput,String... formatContent) {
        log.error(getExceptionInfoTrace(errorCode.getMsg()));
        this.retMsg = errorCode.getMsg();
        this.retCode=errorCode.getCode();
        this.otherMsg = StringTools.format(formatInput,formatContent);
    }


//    public BusinessException(String retMsg, Throwable e) {
//        super(retMsg, e);
//        this.retMsg = retMsg;
//    }
//
//    public BusinessException(String retCode, String retMsg, Throwable e) {
//    	super(retMsg, e);
//    	this.retMsg=retMsg;
//    	this.retCode=retCode;
//    }

    public BusinessException(Throwable t) {
        super(t);
    }

    public String getCode() {
        return retCode;
    }

    public String getMsg() {
        return retMsg;
    }

    String getExceptionInfoTrace(String msg){
        StringBuilder sbException = new StringBuilder(msg);
        StackTraceElement[] eles = getStackTrace();
        for (int i = 0; i < eles.length; i++) {
            StackTraceElement ele = eles[i];
            //只取前几行，方便获取具体报错位置
            if (ele.getClassName().indexOf(basePackage)==-1 || ele.getMethodName().equals("invoke") || ele.getClassName().indexOf("CGLIB")>-1){
                continue;
            }
            sbException.append(MessageFormat.format("\n  {0}.{1}({2}:{3})", ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));
        }
        return sbException.toString();
    }



}
